"""
数据库配置和初始化
"""

from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

from config.logging_config import get_logger
from constant.settings import settings

logger = get_logger(__name__)

# 创建数据库引擎
engine = create_engine(
    settings.DATABASE_URL,
    echo=settings.DEBUG,
    pool_pre_ping=True,
    pool_recycle=300
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基础模型类
Base = declarative_base()


def get_db_session():
    """获取数据库会话（用于FastAPI依赖注入）"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


async def init_database():
    """初始化数据库"""
    try:
        # 导入所有模型以确保表被创建
        from pojo.ai_web_scene_model import AIWebSceneModel
        from pojo.ai_web_dialog_model import AIWebDialogModel
        from pojo.ai_web_agent_model import AIWebAgentModel
        from pojo.ai_web_tools_model import AIWebToolsModel
        from pojo.ai_web_mcp_tools_model import AIWebMCPToolsModel
        from pojo.ai_web_detail_tools_model import AIWebDetailToolsModel
        from pojo.ai_web_memory_his_model import AIWebMemoryHisModel
        from pojo.ai_web_api_calling_model import AIWebApiCallingModel

        # 创建所有表
        Base.metadata.create_all(bind=engine)
        logger.info("数据库表创建成功")

        # 初始化场景数据
        from scene.init_scene_data import init_scene_data
        db = SessionLocal()
        try:
            init_scene_data(db)
        finally:
            db.close()

    except Exception as e:
        logger.error(f"数据库初始化失败: {e}")
        raise
